package cn.zjj.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class LoginCheckFilter extends ZuulFilter {


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //1.获取请求地址   请求上下文
        RequestContext context = RequestContext.getCurrentContext();
        //请求
        HttpServletRequest request = context.getRequest();
        //地址
        String uri = request.getRequestURI();
        //2.判断地址是否需要过滤
        if (uri.endsWith("login") || uri.endsWith("register")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        response.setContentType("application/json;charset=utf-8");
        String token = request.getHeader("token");
        if(!StringUtils.hasLength(token)){
            try {
                PrintWriter writer = response.getWriter();
                HashMap<String, Object> map = new HashMap<>();
                    map.put("success",false);
                    map.put("message","登录状态失效,请重新登录!");
                    //fastjson工具
                String msg = JSONObject.toJSONString(map);
                //输出到页面
                writer.write(msg);
                //已经被过滤了,需要阻止后续filter执行,
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //如果要放行,返回null就行,不用管
        return null;
    }
}
